package com.atguigu.lease.web.admin.controller.login;


import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "后台管理系统登录管理")
@RestController
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private SystemUserService systemUserService;

    @Operation(summary = "获取图形验证码")
    @GetMapping("login/captcha")
    public Result<CaptchaVo> getCaptcha() {
        CaptchaVo captchaVo = loginService.getCaptcha();
        return Result.ok(captchaVo);
    }

    // 完成 登录
    // 错题笔记：
    // redis 1. 根据键获取值 redis就相当于临时mysql 非关系型数据库
    @Operation(summary = "登录")
    @PostMapping("login")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        String token = loginService.login(loginVo);
        return Result.ok(token);
    }

    @Operation(summary = "获取登陆用户个人信息")
    @GetMapping("info")
    public Result<SystemUserInfoVo> info(HttpServletRequest request) {
//        String access_token = request.getHeader("access_token");
//        if (access_token == null) {
//            // token 不存在  响应用户为登录
//            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
//        }
//
//        // 验证Token是否过期 过期了要重新登录
//        Claims claims = JwtUtil.parseToken(access_token);
//        Long userId = claims.get("userId", Long.class);
//        String userName = claims.get("userName", String.class);

//        Long userId = (Long) request.getAttribute("userId");

        LoginUser loginUser = LoginUserContext.getLoginUser();
        // 根据用户的id查询用户的信息
        SystemUserInfoVo systemUserInfoVo =  systemUserService.getSysUserId(loginUser.getUserId());
        return Result.ok(systemUserInfoVo);

    }
}